// pages/phttps://shop.globalhexi.cn/shop/pingTuan/getPinTuanNewDetailaired_detail/paired_detail.js
const app = getApp();
const getToken= require('../../utils/get_token.js');
const formatTime = require('../../utils/util.js');
const getMemId = require('../../utils/memberId.js');
let memberId = '', openId = '', pageNo=1;
const WxParse = require('../../wxParse/wxParse.js');
let poodId='',ctx;
function getImageInfo(url) {
  return new Promise((resolve, reject) => {
    wx.getImageInfo({
      src: url,
      success: resolve,
      fail: reject,
    })
  })
}
const drawCanvas = (that,imgs,oldPprice,newPrice) => {
  oldPprice=`￥${oldPprice}`;
  newPrice=`￥${newPrice}`;
  async function drawMain(){
    const codePromise =await getImageInfo(imgs);
    ctx.drawImage('../../image/sbg.jpg', 0, 0, 420, 340);
    ctx.drawImage(codePromise.path, 20, 105, 208, 208);
   
    ctx.beginPath()
    ctx.setFillStyle('#ff383d')
    ctx.setFontSize(30)
    ctx.font = 'normal bold 40px Arial,sans-serif '
    ctx.setTextAlign('center')
    ctx.fillText(newPrice, 310, 170)
    ctx.closePath();

    ctx.beginPath();
    ctx.setFontSize(25);
    ctx.setFillStyle('#bfbfbf');
    ctx.fillText(oldPprice, 310, 220);
    ctx.setStrokeStyle('#bfbfbf')
    ctx.moveTo(260, 210);
    ctx.lineTo(380, 210);
    ctx.stroke();
    ctx.closePath();
    ctx.draw(false, function () {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 425,
        height: 339,
        destWidth: 425,
        destHeight: 339,
        canvasId: 'firstCanvas',
        success(res) {
          that.data.targetSharePath = res.tempFilePath;
        }
      })
    }) 
  }
  drawMain();
};

const ckToken = async (that) => {//token确认
  let nTime = Math.floor(new Date().getTime() / 1000);
  let oldTime = wx.getStorageSync('ntime') || 0;
  if (nTime < oldTime)//现在的时间小于到期时间
  {
    thou(that);
  } else {
    await getToken.getToken();
    thou(that);
  }
}
const thou = (that) => {//token没有失效时执行的代码
  if (openId == '') {
    getToken.getOpenId(function (res) {
      wx.setStorageSync('openId', res.data.openId);
      if (memberId == '') {
        getMemId.getMemId(res.data.openId, function (res) {
          if (res.data.flag == 'true') {
            wx.setStorageSync('memberId', res.data.memberId);
          } else {
            wx.redirectTo({ url: '../login/login?id=2&gid=' + poodId })
           }
        })
      }
      openId = res.data.openId;
      addRecord(that);
    });
  } else {
    if (memberId == '') {
      wx.redirectTo({ url: '../login/login?id=2&gid=' + poodId })
    }
    addRecord(that);
  }
  getRule(that);
  likeList(that);
}
const wxHaoWu = (that) => {//分享好物
  wx.request({
    header: { 'content-type': 'application/x-www-form-urlencoded' },
    method: 'POST',
    url: 'https://interface.globalhexi.cn/gift/wxHaoWuQuan/wxHaoWuUpdateGoods',
    data: { goodsId: that.data.goodsId, goodsPinTuanId: poodId},
    success: function (res) {
      if (res.data.flag) {
        that.data.hwShow = true;
        that.data.product = res.data.product_list.product_list[0];
        let url = res.data.product_list.product_list[0].src_wxapp_path;
        delete that.data.product.src_wxapp_path;
        that.data.product.src_mini_program_path = url;
      } else {
        that.data.hwShow = false;
      }
      that.setData({
        hwShow: that.data.hwShow,
        product:that.data.product
      })
    }
  })
};
const addRecord = (that) => {//添加浏览记录
  let params = [ 'shop/pingTuan/addHuoPinViewRecord', {"openId": openId,"memberId":memberId,"goodsPinTuanId": poodId,"seeType":2}]
  getToken.getData(function (res) {
  
  }, ...params)
};
const likeList = (that) => {//猜你喜欢
    that.setData({ hidden: false })
  let params = ['shop/pingTuan/guessYouLike', {"openId":openId,"memberId":memberId,"pageSize": pageNo,"seeType":2,"pinTuanGoodsId": poodId,"orderSn":""}]
    getToken.getData(function (res) {
      let rows = res.data.rows;
      if (rows.length > 0) {
        for (let i = 0; i < rows.length; i++) {
         // rows[i].goodsImageStore = rows[i].goodsImageStore.substring(1, rows[i].goodsImageStore.length - 1);
          rows[i].goodsImageStore = JSON.parse(rows[i].goodsImageStore);
          rows[i].img = 'https://www.globalhexi.com/' + rows[i].goodsImageStore[0].path + '/small/' + rows[i].goodsImageStore[0].id + '.jpg';
          rows[i].intPinPrice = (rows[i].intPinPrice / 100).toFixed(2);
          rows[i].intPrice = (rows[i].intPrice / 100).toFixed(2);
          that.data.lkList.push(rows[i]);
        }
      }
      that.setData({
        lkList: that.data.lkList,
        hidden: true
      })
    }, ...params)
};
const getRule = (that) => {//规则
  let params = ['common/noteBook/getNoteBook', {"id":"7D484691DA9E488A863BFF7A8A0617B1"}]
  getToken.getData(function (res) {
    WxParse.wxParse('rule', 'html', res.data.content, that, 5);
  }, ...params)
};
const addcollect = (that) => {//添加取消收藏
  if (that.data.boolT){
    that.data.boolT=false;
    let params = [ 'shop/pingTuan/addHuoPinCollecRecord', {"openId": openId,"memberId": memberId,"goodsPinTuanId":poodId,"seeType":2,"isStatus": that.data.acType}]
    getToken.getData(function (res) {
      that.data.timer=setTimeout(function () { that.data.boolT = true; }, 500)
      if (that.data.acType == 1)//收藏
      {
        that.data.acimg = '../../image/tab_shoucang1.png';
        that.data.acname = '已收藏';
        wx.showToast({
          title: '收藏成功',
          icon: 'success',
          duration: 2000
        })
      } else {
        that.data.acimg = '../../image/tab_shoucang.png';
        that.data.acname = '收藏';
        wx.showToast({title:'取消收藏成功',icon:'none',duration: 1000})
      }
      that.setData({
        acimg: that.data.acimg,
        acname: that.data.acname
      })
    }, ...params)
  }
};
const adzo=function(num) {
	if (num < 10)
		return ('0' + num);
	else
		return num;
}
const fresh=function(that,data,dom){
	if (data <= 0) {
		dom.times = '00:00:00';
		dom.current = false;
	} else {
    let h = adzo(parseInt(data / 3600));
    let m = adzo(parseInt((data / 60) % 60));
    let s = adzo(parseInt(data % 60));
		dom.times = h + '：' + m + '：' + s;
	}
}

const indexList = (that) => {
  that.setData({hidden: false})
  wx.request({
    header: { 'content-type': 'application/x-www-form-urlencoded' },
    method: 'POST',
    url: 'https://interface.globalhexi.cn/shop/pingTuan/getPinTuanNewDetail',
    data: { id: poodId, openId: openId, membId: memberId },
    success: function (res) {
      console.log(res.data);
      let data=res.data;
      let goods = data.result;
      goods.bestShow=data.isBest;//新人专享图标
      goods.slShow=goods.goodsPinTuanVo.tuanSetType==1?true:false;//社邻拼图标
      that.data.scNum =goods.goodsPinTuanVo.memberSum;//参团人数
      goods.goodsPinTuanVo.endTime = new Date(goods.goodsPinTuanVo.endTime);
      goods.goodsPinTuanVo.endTime = formatTime.formatTime(goods.goodsPinTuanVo.endTime);//开团结束时间
      goods.goodsPinTuanVo.intPrice = (goods.goodsPinTuanVo.intPrice / 100).toFixed(2);
      goods.goodsPinTuanVo.goodsPinTuanSetIntVo.intPrice = (goods.goodsPinTuanVo.goodsPinTuanSetIntVo.intPrice / 100).toFixed(2);
      that.data.ntShow=!data.isNationaSales;//是否全国销售,false表示不是全国销售
      goods.isGroupBuy = data.isGroupBuy;//自提
      if(goods.isGroupBuy&&data.goodsParentCategoryId=='A15EB4444BCC4237995950D653BBF7AE'){
         goods.mpShow=true;				  
      }
      if(goods.busPinTuanVo.logo.indexOf("http://image.globalhexi.com")==-1)
			{
				goods.busPinTuanVo.logo="http://image.globalhexi.com/"+goods.busPinTuanVo.logo;
      }
       //商品种类
       if(data.products!=null){
         for(let i=0;i<data.products.length;i++){
          data.products[i].pro_image =`http://image.globalhexi.com/${data.products[i].pro_image}`;
          that.data.urlList.push(data.products[i].pro_image);
          that.data.pdList.push(data.products[i])
         }   
       }
      let adeaList = [];//自提地址
      if (data.zitiAddressList.length > 0) {//自提地址修改
        for (let i = 0; i <data.zitiAddressList.length; i++) {
          if (data.zitiAddressList[i] != null) {
            data.zitiAddressList[i].name = data.zitiAddressList[i].zitiName;
            data.zitiAddressList[i].areaStore = JSON.parse(data.zitiAddressList[i].areaStore);
         //   data.zitiAddressList[i].address = data.zitiAddressList[i].areaStore.displayName + data.zitiAddressList[i].address;
            adeaList.push(data.zitiAddressList[i]);
          }
        }
      }
      if(data.goodsSpecList.length>0)//购买规格展示，表示有规格 
			  {
          that.data.ggShow=true;//有规格
          for (let k = 0; k < data.goodsSpecList.length; k++)
          {
            that.data.SpecList[k] = { name: data.goodsSpecList[k].name, ul: [] };
            for (let t = 0; t < data.goodsSpecList[k].specificationValueList.length; t++) {
              that.data.SpecList[k].ul.push({ productId: data.goodsSpecList[k].specificationValueList[t].id, name:data.goodsSpecList[k].specificationValueList[t].name, disable: null, trueS: false, row: k, current: false })
            }
          }  
          if(that.data.SpecList.length>=2){
            that.data.twogShow=true;//双规格
          }
        }
      that.data.goodsId =goods.goodsPinTuanVo.goodsId;
      that.data.tList=goods.goodsPinTuanVo.goodsPinTuanSetIntVo.setPriceList;//团区间的所有信息
      that.data.storeNum=goods.goodsPinTuanVo.goodsPinTuanSetIntVo.nums;//商品剩余总份数
      let pArr = [],tocmeArr=[]; //价格区间的所有价格  .返利
      for(let i=0;i<that.data.tList.length;i++)//寻找开团人数区间 
			{
        tocmeArr.push(that.data.tList[i].tuanInCome);
        that.data.tList[i].caprice=that.data.tList[i].intPinPrice/100;
        that.data.tList[i].num=0;//无规格时选择的数量
				if(that.data.tList[i].minNum==that.data.tList[i].maxNum)
				{
					that.data.tList[i].allNum=that.data.tList[i].minNum;
				}else{
					that.data.tList[i].allNum=that.data.tList[i].minNum+'-'+that.data.tList[i].maxNum;
        }
        if(that.data.ggShow){//判断是否有规格
          for (let j = 0; j < that.data.tList[i].tuanSetProductList.length; j++) {
            pArr.push(that.data.tList[i].tuanSetProductList[j].intPinPrice)
          }
        }else{
          pArr.push(that.data.tList[i].intPinPrice)
        }
			}
      let max = Math.max(...pArr) / 100;
      let min = Math.min(...pArr) / 100;
      that.data.minPrice=`${min}元 `;
      goods.ggPrice=max == min?max:`${min}-${max}`;
      let maxCome=Math.max(...tocmeArr)/100;
      let minCome=Math.min.apply(null,tocmeArr)/100;
      goods.comePrice=maxCome==minCome?minCome:`${minCome}-${maxCome}`;
        if(maxCome!=0)
        {
          goods.cpShow=true;
        }
        that.data.comeP=that.data.tList[0].tuanInCome/100;//返利初始值
      if (goods.isfavorite)//已经收藏 
      {
        that.data.acType = 1;
        that.data.acimg = '../../image/tab_shoucang1.png';
        that.data.acname='已收藏';
      }
      that.data.pctId=goods.goodsPinTuanVo.productId;//初始的货品id
      let start = goods.goodsPinTuanVo.desc.indexOf('<style');
      let end = goods.goodsPinTuanVo.desc.indexOf('</style>');
      if(start!=-1&&end!=-1)
      {
        let deletecontent = goods.goodsPinTuanVo.desc.slice(start, end);
        goods.goodsPinTuanVo.desc=goods.goodsPinTuanVo.desc.replace(deletecontent,'')
      }
      let article = goods.goodsPinTuanVo.desc.replace('<!DOCTYPE html>', '');
      WxParse.wxParse('article','html', article, that, 5);
      let imgs = [];
      let Urls = JSON.parse(goods.goodsPinTuanVo.img);
      if (Urls.length > 0) {
        for (let i = 0; i < Urls.length; i++)//大图
        {
          let Url = `https://www.globalhexi.com/${Urls[i].path}/big/${Urls[i].id}.jpg`;
          imgs.push({content:Url,video:false,poster:''});
        }
        goods.bigImg=imgs[0].content;
      }
      let videos=[];
      if(data.goodsVideoState==1||data.goodsVideoState==3)//审核通过，添加视频
			{
				  videos=[{content:data.goodsVideoUrl,video:true,poster:goods.bigImg}]
			  	imgs.splice(0,1);//删除第一张图片
      }
      let imgList=videos.concat(imgs);
      if(data.goodsVideoState==1||data.goodsVideoState==3){//审核通过，添加视频
			  that.videoContext = wx.createVideoContext('myVideo')
      }
       //单独购买 商品是否下架 current参数
     let current=true;
     if (!goods.goodsPinTuanVo.pIsMaketable || !goods.goodsPinTuanVo.goodsPinTuanSetIntVo.open)
      {
        current=false;
      }
      that.data.limitNum=goods.goodsPinTuanVo.goodsPinTuanSetIntVo.limitNums;
      if(that.data.limitNum==0){
        that.data.olist.push({'name': '直接购买', 'classiy': 0,'img':goods.bigImg,'gname':goods.goodsPinTuanVo.goodsName,'isbest':goods.bestShow,'twogShow':that.data.twogShow,'id': goods.goodsPinTuanVo.goodsPinTuanSetIntVo.id,'limit': goods.goodsPinTuanVo.goodsPinTuanSetIntVo.limitNums, current,'zt':goods.isGroupBuy, 'zitiAddressList': adeaList});
      }
        that.data.olist.push({'name': '拼团购买', 'classiy': 1,'img':goods.bigImg,'gname':goods.goodsPinTuanVo.goodsName,'isbest':goods.bestShow,'twogShow':that.data.twogShow,'id': goods.goodsPinTuanVo.goodsPinTuanSetIntVo.id,'limit': goods.goodsPinTuanVo.goodsPinTuanSetIntVo.limitNums, current,'zt': goods.isGroupBuy, 'zitiAddressList': adeaList});
      if (goods.list != null) {//团列表
        goods.mlShow=true;
        if (goods.list.length==1)
        {
          that.data.multiple=1;
        }
        for (let j = 0; j < goods.list.length; j++) {
          var dete = goods.list[j].remainderHour * 3600 + goods.list[j].remainderMin * 60 + goods.list[j].remainderSec;
          goods.list[j].time = dete;
          goods.list[j].price = (goods.list[j].intPinPrice/100).toFixed(2);
          goods.list[j].store = goods.list[j].reminderMember;
          goods.list[j].limit = goods.list[j].limitNums;
          goods.list[j].classiy = 2;
          goods.list[j].addressMsg = JSON.parse(goods.list[j].addressMsg);
          if (goods.list[j].memberLogo.indexOf('http') == -1) {
            goods.list[j].memberLogo = 'https://www.globalhexi.com/' + goods.list[j].memberLogo;
          }
          if (!goods.goodsPinTuanVo.pIsMaketable || !goods.goodsPinTuanVo.goodsPinTuanSetIntVo.open) {//团商品是否下架-没下架
              goods.list[j].current = false;
            }
            else {
              goods.list[j].current = true;
            }
          fresh(that, goods.list[j].time, goods.list[j]);
          that.data.aList.push(goods.list[j]);
        }
        that.data.inset=setInterval(function () {
           for (let i = 0; i < that.data.aList.length; i++)
          {
            that.data.aList[i].time--;
             fresh(that, that.data.aList[i].time, that.data.aList[i])
            that.setData({
              aList: that.data.aList
            })
          } 
        }, 1000)
      }
      that.setData({
        goods: goods,
        imgUrls: imgList,
        ggShow:that.data.ggShow,
        ntShow: that.data.ntShow,
        tempList:that.data.tempList,
        storeNum:that.data.storeNum,
        twogShow:that.data.twogShow,
        multiple: that.data.multiple,
        scNum: that.data.scNum,
        SpecList: that.data.SpecList,
        tList: that.data.tList,
        aList: that.data.aList,
        olist: that.data.olist,
        acimg: that.data.acimg,
        acname: that.data.acname,
        comeP:that.data.comeP,
        limitNum:that.data.limitNum,
        hidden: true
      })
      ctx = wx.createCanvasContext('firstCanvas');
      drawCanvas(that,goods.bigImg,goods.goodsPinTuanVo.intPrice,min);
     // wxHaoWu(that);
    }

  })
};
const getOneTemp=function(that,arr,stlitNum){//有1个规格时寻找临时数组
  that.data.tempList=[];
  arr.forEach(function(ele,index,arr){
      if(index==0){//临时加的
        ele.num=stlitNum;
      }
      ele.name=ele.speciValueStoreList[0].name;
      that.data.tempList.push(ele)
  })
  that.setData({tempList:that.data.tempList})
}

const changeSpe=function(that,productId,stlitNum){//有2个规格时寻找临时数组
  for(let i=0;i<that.data.SpecList[1].ul.length;i++){
     if(productId==that.data.SpecList[1].ul[i].productId){
        that.data.SpecList[1].ul[i].show=true;
        that.data.tempList=[];//临时数组
        that.data.tallList.forEach(function(ele,index,arr){
          if(productId==ele.speciValueStoreList[0].id){              
            ele.name=ele.speciValueStoreList[1].name;
              that.data.tempList.push(ele)
          }
          if(productId==ele.speciValueStoreList[1].id){
            ele.name=ele.speciValueStoreList[0].name;
            that.data.tempList.push(ele)
          }
        })
       }else{
        that.data.SpecList[1].ul[i].show=false;
       } 
  }
  that.data.tempList[0].num=stlitNum;
  let fId=that.data.tempList[0].id;
  that.data.tallList.forEach(function(ele,index,arr){
    if(fId==ele.id){
     ele.num=1;
    }
  })

  that.setData({
    tempList:that.data.tempList,
    SpecList:that.data.SpecList
  })
}
const initialization=function(that,obj,bool){//商品设置初始值
  if(obj.store>0)
  {
     for(let i=0;i<that.data.tList.length;i++){
       if(obj.id==that.data.tList[i].id){
        that.data.tList[i].show=true;
        that.data.limitMax=that.data.tList[i].maxNum;
        that.data.limitMin=that.data.tList[i].minNum;
       }else{
        that.data.tList[i].show=false;
       }
     }
     that.data.tallList=[];
     obj.tuanSetProductList.forEach(function(ele,index,arr){
     if(bool&&!that.data.ggShow){//单独购买而且没有规格
      ele.num=that.data.limitMin;
     }else{
      ele.num=0;
     }
     ele.price=(ele.intPinPrice/100).toFixed(2);
     that.data.tallList.push(ele)
    })
    if (that.data.ggShow)//是否有规格
    {  
      let stlitNum=bool?that.data.limitMin:1;
        if(that.data.twogShow){
        changeSpe(that,that.data.SpecList[1].ul[0].productId,stlitNum);
        }else{//单规格取临时数组
        getOneTemp(that,that.data.tallList,stlitNum)
        }

    }else{//无规格
      if(!bool){
        that.data.tallList[0].num=1;
      }
      that.data.tempList=that.data.tallList;
      that.data.tempList[0].name='购买数量';
      that.setData({tempList:that.data.tempList})
    }
    that.data.allNum = that.data.tallList.reduce(function (prev, cur) {
      return cur.num + prev;
   }, 0); 
   that.data.allMoney = that.data.tallList.reduce(function (prev, cur) {
    let oMoney=(cur.intPinPrice/100)*cur.num;
    return oMoney + prev;
  }, 0);
  that.data.allMoney=that.data.allMoney.toFixed(2);
    that.setData({
      tallList:that.data.tallList,
      tList:that.data.tList,
      allMoney:that.data.allMoney,
      allNum:that.data.allNum
    })
  }
}
// const jia=function(that,id,limit){
//   let num=0;
//   that.data.allNum = that.data.tallList.reduce(function (prev, cur) {
//      return cur.num + prev;
//   }, 0); 
//   if(limit>that.data.allNum){
//     for(let i=0;i<that.data.tallList.length;i++){
//       if(id==that.data.tallList[i].id){
//          that.data.tallList[i].num+=1;
//          that.data.allNum+=1;
//          num=that.data.tallList[i].num;
//       }
//     }
//     for(let j=0;j<that.data.tempList.length;j++){
//       if(id==that.data.tempList[j].id){
//          that.data.tempList[j].num=num;
//       }
//     }
//     that.data.allMoney = that.data.tallList.reduce(function (prev, cur) {
//       let oMoney=(cur.intPinPrice/100)*cur.num;
//       return oMoney + prev;
//     }, 0);
//     that.data.allMoney=that.data.allMoney.toFixed(2);
//     that.setData({
//       tallList:that.data.tallList,
//       tempList:that.data.tempList,
//       allMoney:that.data.allMoney,
//       allNum:that.data.allNum
//     })
//   }
// }

const jia=function(that,id,limit){//数量加事件 limit是限制的值，
  let num=0,iIndex=0;
  // that.data.allNum = that.data.tallList.reduce(function (prev, cur) {
  //    return cur.num + prev;
  // }, 0); 
  that.data.tallList.forEach(function(ele,index,arr){
    if(id==ele.id){
      iIndex=index;
    }else{
      ele.num=0
    }
  })
  that.data.allNum = that.data.tallList[iIndex].num;//当前product增加时，其他的都为0
  if(limit>that.data.allNum){
      that.data.tallList[iIndex].num+=1;
      that.data.allNum+=1;
      num=that.data.tallList[iIndex].num;
    for(let j=0;j<that.data.tempList.length;j++){
      if(id==that.data.tempList[j].id){
         that.data.tempList[j].num=num;
      }else{
         that.data.tempList[j].num=0;
      }
    }
    that.data.allMoney=num*(that.data.tallList[iIndex].intPinPrice/100);
    that.data.allMoney=that.data.allMoney.toFixed(2);
    that.setData({
      tallList:that.data.tallList,
      tempList:that.data.tempList,
      allMoney:that.data.allMoney,
      allNum:that.data.allNum
    })
  }else{
    wx.showToast({title:that.data.message,icon:'none',duration: 1000})
  }
}
const jian=function(that,id,limit){//数量加事件 limit是限制的最小值，
  let num=0;
  that.data.allNum = that.data.tallList.reduce(function (prev, cur) {
     return cur.num + prev;
  }, 0); 
  if(limit<that.data.allNum){
    for(let i=0;i<that.data.tallList.length;i++){
      if(id==that.data.tallList[i].id){
         if(that.data.tallList[i].num>0){
          that.data.tallList[i].num-=1;
          that.data.allNum-=1;
         }
         num=that.data.tallList[i].num;
      }
    }
    for(let j=0;j<that.data.tempList.length;j++){
      if(id==that.data.tempList[j].id){
        that.data.tempList[j].num=num;
      }
    }
    that.data.allMoney = that.data.tallList.reduce(function (prev, cur) {
      let oMoney=(cur.intPinPrice/100)*cur.num;
      return oMoney + prev;
    }, 0);
    that.data.allMoney=that.data.allMoney.toFixed(2);
    that.setData({
      tallList:that.data.tallList,
      tempList:that.data.tempList,
      allMoney:that.data.allMoney,
      allNum:that.data.allNum
    })
  }
}
Page({
 
  /**
   * 页面的初始数据
   */
  data: {
    goods:{},
    imgUrls: [],
    urlList:[],
    pdList:[],
    wHeight:app.globalData.windowHeight,
    acimg:'../../image/tab_shoucang.png',
    acname:'收藏',
    acType:0,
		indicatorDots: true,
		indicatorC: "#fff",
		indicatorAC: "red",
		autoplay: false,
		interval: 5000,
		duration: 500,
		circular: true,
    multiple:2,
    aList:[],
		dList: [],
    mList: [],
    lkList:[],
    SpecList:[],//规格类型
    tempList:[],//临时一种规格类型
    tallList:[],//临时一个区间所有规格类型
    tList:[],
    ptsList:[],
    comeP:0,
    cindex:0,
    allNum:0,
    allMoney:0,
    cpShow:false,
    minPrice:'',
    mPrice:'',
    inset:'',
    timer:'',
    targetSharePath:'',
		open:false,
    sOpen:false,
    mopen:false,
    hwShow:false,
    ntShow:false,
    isSpecial:false,
    cqShow:false,
    cgShow:false,
    qjShow:true,
    ggShow:false,
    twogShow:false,
    limitNum:0,
    limitMax:0,
    limitMin:0,
    isStopBodyScroll:'auto',
    pctId:'',
    gtype:'',
		olist:[],
    goodsId:'',
    tuanId:'',
    animationAddressMenu: {},
    animationSpeMenu:{},
    addressMenuIsShow: false,
    message:'已超过拼团份数限制',
    product: {
      "item_code": "1A4EBC8F5C83469C9AAF7403EA617D05",
      "title": "阳晨竹炭细丝成人软毛牙刷【1份3支】",
      "desc": "product_description",
      "category_list": [
        "短袖衬衫"
      ],
      "image_list": [
        "https://www.globalhexi.com/oss/img/image/20190515/small/3c6cbcb8c2a94764b624e619a25e7cd2.jpg"
      ],
      "src_mini_program_path": "pages/paired_detail/paired_detail?scene=1A4EBC8F5C83469C9AAF7403EA617D05",
      "sku_list": [
        {
          "sku_id": "SKU_ID",
          "price": 12345,
          "original_price": 67890,
          "status": 1,
          "sku_attr_list": [
            {
              "name": "颜色",
              "value": "白色"
            }
          ]
        }
      ],
      "brand_info": {
        "name": "品牌名、小程序名",
        "logo": "http://xxxxx"
      }
    },
		boolT: true,
    bool: true,
    boxShow:true,
		hidden:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.videoContext = wx.createVideoContext('myVideo')
    poodId = options.scene;
    let shareId=options.shareId||'';
    if(shareId!='')
    {
      wx.setStorageSync('shareId', shareId);
    }
    memberId = wx.getStorageSync('memberId') || '';
    openId = wx.getStorageSync('openId') || '';
    pageNo=1;
    indexList(that);
    ckToken(that);
    // 初始化动画变量
    let animation = wx.createAnimation({
      duration: 500,
      transformOrigin: "50% 50%",
      timingFunction: 'ease',
    })
    that.animation = animation;
  },
  selectDistrict: function (e) {//点击分享
    let that = this
    // 如果已经显示，不在执行显示动画
    if (that.data.addressMenuIsShow) {
      return
    }
    // 执行显示动画
    that.startAddressAnimation(true);
  },
  // 执行分享动画
  startAddressAnimation: function (isShow) {
    let that = this
    if (isShow) {
      // vh是用来表示尺寸的单位，高度全屏是100vh
      that.animation.translateY(0 + 'vh').step()
    } else {
      that.animation.translateY(35 + 'vh').step()
    }
    that.setData({
      animationAddressMenu: that.animation.export(),
      addressMenuIsShow: isShow,
    })
  },
  // 执行规格动画
  startSpeAnimation: function (isShow) {
    let that = this
    if (isShow) {
      // vh是用来表示尺寸的单位，高度全屏是100vh
      that.animation.translateY(0 + 'vh').step()
    } else {
      that.animation.translateY(50 + 'vh').step()
    }
    that.setData({
      animationSpeMenu: that.animation.export()
    })
  },
  // 点击规格选择取消按钮
  hidespeSelected: function (e) {
    this.startSpeAnimation(false)
    this.setData({
      cqShow:false,
      cgShow:false,
      spShow:false,
    })
  },
  // 点击蒙版时取消组件的显示
  hideCitySelected: function (e) {
    this.startAddressAnimation(false)
  },
  jiaA(e){//数量加事件
    let that = this;
    let id = e.currentTarget.dataset.id;
    let limit=that.data.limitMax;
    that.data.message=`已超过拼团份数限制`;
    if(that.data.limitNum>0){//商品有购买限制
      limit=that.data.limitNum;
      that.data.message=`商品限购${limit}份`;
    }
    jia(that,id,limit)

  },
  jianA(e){//数量减事件
    let that = this;
    let id = e.currentTarget.dataset.id;
    jian(that,id,1);
  },
  jiaB(e){//单独购买数量加事件
    let that = this;
    let id = e.currentTarget.dataset.id;
  //  let limit=that.data.storeNum;
    let limit=that.data.limitMax;
    that.data.message=`超过购买份数限制`;
    jia(that,id,limit);
  },
  jianB(e){//单独购买数量减事件
    let that = this;
    let id = e.currentTarget.dataset.id;
    jian(that,id,1);
  },
  jiaC(e){//参团数量加事件
    let that = this;
    let id = e.currentTarget.dataset.id;
    let limit=that.data.rmember;
    if(that.data.limitNum>0){//商品有购买限制
      limit=that.data.limitNum;
    }
    jia(that,id,limit)
  },
  jianC(e){//参团数量减事件
    let that = this;
    let id = e.currentTarget.dataset.id;
    jian(that,id,1);
  },
  change_or:function(e){//团份数选择
    let that = this;
    let id = e.currentTarget.dataset.id;
    let obj={};
    for(let i=0;i<that.data.tList.length;i++)
	  {
      if(that.data.tList[i].id==id)
        {
          obj=that.data.tList[i];
        }
    }	
    initialization(that,obj,false);
  },
  change_A:function(e){//单独购买团份数选择
    let that = this;
    let id = e.currentTarget.dataset.id;
    let obj={};
    for(let i=0;i<that.data.tList.length;i++)
	  {
      if(that.data.tList[i].id==id)
        {
          obj=that.data.tList[i];
        }
    }	
    initialization(that,obj,true);
  },
  change_gg(e){//规格点击事件
    let that = this;
    let productId = e.currentTarget.dataset.productid;
    changeSpe(that,productId,1);
  
  },
  change_dg(e){
    let that = this;
    let productId = e.currentTarget.dataset.productid;
    changeSpe(that,productId,that.data.limitMin);
  },
  sure: function (e) {//底部按钮开团
    let that=this;
    let iclassiy = e.currentTarget.dataset.iclassiy;
      if (that.data.boolT) {
        that.data.boolT = false;
        if (iclassiy== 0)//单独购买
        {
            that.startSpeAnimation(true);//动画
            that.setData({spShow: true})
            initialization(that,that.data.tList[0],true);
        } else {//伙拼开团
            that.startSpeAnimation(true);
            that.setData({cqShow: true})
            initialization(that,that.data.tList[0],false);
        }
        that.data.timer =setTimeout(function () { that.data.boolT = true; }, 500)
      }
  },
  join:function(e){//参团按钮打开弹窗
    let that = this;
    let setId = e.currentTarget.dataset.setid;
    that.data.tuanId = e.currentTarget.dataset.id;
    that.data.rmember = e.currentTarget.dataset.rmember;
    for(let i=0;i<that.data.tList.length;i++)
    {
      if(that.data.tList[i].pinTuanSetPriceId==setId)//购买的份数区间
      {
        initialization(that,that.data.tList[i],false)
        that.data.cgShow=true;
        that.startSpeAnimation(true);
        that.setData({cgShow: that.data.cgShow})
      }
    }
	},
  gobuy:function(e){//弹窗开团
    let that = this;
    if(that.data.allNum>0){
      let pood=that.data.olist[that.data.olist.length-1];
      pood.tallList=that.data.tallList;//已选货品数组
      pood.allNum=that.data.allNum;//已经选择的总份数
      pood.allMoney=that.data.allMoney;//已经选择的总计钱
      pood.max=that.data.limitMax;//已经选择区间最大数
      pood.min=that.data.limitMin;//已经选择的区间最小数
      pood.store=that.data.storeNum;//已经选择的区间库存
      pood.busId=that.data.goods.busPinTuanVo.id;
      wx.setStorageSync('pood', pood);
      wx.navigateTo({
        url: '../paired_order/paired_order?id=' + poodId
      })
    }else{
      wx.showToast({title:'请选择商品购买数量',icon:'none',duration: 1000})
    }
  },
  onebuy:function(e){//单独购买规格型
    let that = this;
    if(that.data.allNum>=that.data.limitMin){
      let pood=that.data.olist[0];
      pood.tallList=that.data.tallList;//已选货品数组
      pood.allNum=that.data.allNum;//已经选择的总份数
      pood.allMoney=that.data.allMoney;//已经选择的总计钱
      pood.max=that.data.limitMax;//已经选择区间最大数
      pood.min=that.data.limitMin;//已经选择的区间最小数
      pood.store=that.data.storeNum;//已经选择的区间库存
      pood.busId=that.data.goods.busPinTuanVo.id;
      wx.setStorageSync('pood', pood);
      wx.navigateTo({
        url: '../paired_order/paired_order?id=' + poodId
      })
    }else{
      wx.showToast({title:`商品${that.data.limitMin}份批`,icon:'none',duration: 1000})
    }
  },
  ctbuy:function(e){//弹窗参团
    let that = this;
    if(that.data.allNum>0){
      let pood=that.data.olist[that.data.olist.length-1];
      pood.tallList=that.data.tallList;//已选货品数组
      pood.allNum=that.data.allNum;//已经选择的总份数
      pood.allMoney=that.data.allMoney;//已经选择的总计钱
      pood.lastNum=that.data.rmember;//剩余份数
      pood.store=that.data.storeNum;//已经选择的区间库存
      pood.pinId=that.data.goods.goodsPinTuanVo.id;
      wx.setStorageSync('ctpood', pood);
      if (that.data.boolT) {
        that.data.boolT = false;
        wx.navigateTo({
          url: '../pairedk_order/pairedk_order?tuanId=' + that.data.tuanId,
          success: function () {
            that.data.timer =setTimeout(function () {that.data.boolT = true;}, 500)
          }
        })
      }  
    }else{
      wx.showToast({title:'请选择商品购买数量',icon:'none',duration: 1000})
    }   
  },
 
  getMore:function(e){//查看更多弹窗
    let that = this;
    that.setData({
      isStopBodyScroll: that.data.wHeight+'px',
      boxShow: false
    })
  },
  closeMore:function(){
    let that = this;
    that.setData({
      isStopBodyScroll: 'auto',
      boxShow: true
    })
  },
  goIndex:function(e){//去首页
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      wx.reLaunch({
        url: '../index/index',
        success: function () {
          that.data.timer = setTimeout(function () {that.data.boolT = true;}, 500)
        }
      })
    }
  },
  go_bus:function(e){
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false; 
      wx.navigateTo({
        url: '../shop/shop?id=' + e.currentTarget.dataset.id,
        success: function () {
          that.data.timer =setTimeout(function () {that.data.boolT = true;}, 500)
        }
      })
    }
  },
  go_sale:function(e){
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      wx.navigateTo({
        url: '../sale/sale?id=' + that.data.goodsId ,
        success: function () {
          that.data.timer = setTimeout(function () {that.data.boolT = true;}, 500)
        }
      })
    }
  },
  addCo:function(e){//收藏
    let that = this;
    if (that.data.acType==0)
    {
      that.data.acType=1;
    }else{
      that.data.acType = 0;
    }
    addcollect(that);
  },
  enter: function (e) {
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      wx.navigateTo({
        url: '../paired_detail/paired_detail?scene=' + e.currentTarget.dataset.id,
        success: function () {
          that.data.timer =setTimeout(function () {that.data.boolT = true;}, 500)
        }
      })
    }
  },
  go_card:function(e){
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      wx.navigateTo({
        url: '../card/card?id=' + poodId,
        success: function () {
          that.data.timer =setTimeout(function () {that.data.boolT = true;}, 500)
        }
      })
    } 
  },
  preImage:function(e){
    let that=this;
    let current = e.target.dataset.src;
    wx.previewImage({
      current: current,
      urls:that.data.urlList
    })
  },

  selectdC:function(e){//规格选择c单独购买
    let that = this;
    let thisId = e.currentTarget.dataset.id;
    let current = e.currentTarget.dataset.current;
    let rows =e.currentTarget.dataset.rows;
    let disable = e.currentTarget.dataset.disable;
  //disable==null,表示可以点击 rows表示第几种规格 current是非被选中 thisId 是id
  //trueS

    if(disable==null)//表示没有被限制，可以点击
    {
        let index=0;
        let arrId=[];	
        if (current)//取消所有选择
        {
          that.data.ccList.forEach((item,index,arr)=>{
            item.ul.forEach((sitem,sindex,sarr)=>{
               sitem.current=false;
               sitem.disable=null;
            })
          })
          that.setData({boolc:false})
        }else{//开始选中
          that.data.ccList.forEach((item,index)=>{ //取消同行
            if(index==rows){
              item.ul.forEach((sitem)=>{sitem.current=false;})
            }
          })
          that.data.ptsList.forEach((item,index)=>{//通过id找出与这个型号所有匹配的类型
            item.pro_specs.forEach((sitem)=>{
              if (thisId ==sitem) {
                arrId.push.apply(arrId,item);// arrId=[...arrId,...item]; 
              }
            })
          })
          arrId=[...new Set(arrId)];
          that.data.ccList.forEach((item,index)=>{
            item.ul.forEach((sitem)=>{
            //取消被限制的//disable==null表示可以点击。disable==数字时表示被当前数字行的限制了。
            if (rows == sitem.disable){
                sitem.disable = null;
             }
             //当前点击的dom增加active
             if (thisId== sitem.productId) {
                  sitem.current = true;
             }
             //给匹配的li加上trueclass名称,表示第二，及第三种可与选择的规格（trueS用于过度，不可见）
              arrId.forEach((titem)=>{
                if(titem==sitem.productId){
                  sitem.trueS=true;
                }
              }) 
            })
          })
        for (let j = 0; j < that.data.ccList.length; j++) {
          for (let k = 0; k <that.data.ccList[j].ul.length; k++) {         
            if (rows != that.data.ccList[j].ul[k].row &&that.data.ccList[j].ul[k].trueS == false) {//给其他行不能点击的元素的disable加上数字，取消点击          
              that.data.ccList[j].ul[k].disable = rows;
            }
            that.data.ccList[j].ul[k].trueS = false;//回复到默认值trueS值是用来过度的
          }
        }
        for (let j = 0; j < that.data.ccList.length; j++)//确定
        {
          for (let k = 0; k < that.data.ccList[j].ul.length; k++) 
          {
            if (that.data.ccList[j].ul[k].current==true)
            {
              index++;
              if (index == that.data.ccList.length)//几种规格都选择完成时
              {
                let productId=domo(that,that.data.ptsList);
                for(let z=0;z<that.data.ptsList.length;z++)
                {
                  if (productId == that.data.ptsList[z].pro_id)
                  {
                    that.data.olist[0].productId = productId;
                    for(let i=0;i<that.data.pdList.length;i++){
                      if(productId==that.data.pdList[i].pro_id){
                        // that.data.gcImg=that.data.pdList[i].pro_image;
                        // that.setData({gcImg:that.data.gcImg})
                      }
                    }
                    if(that.data.ptsList[z].pro_store>0)
                    {
                      that.setData({boolc:true})
                    }
                  }
                }
              }
            }
          }
        }
      } 
      that.setData({ccList:that.data.ccList})		
  }	
  },
  /**
  * 生命周期函数--监听页面隐藏
  */
  onHide: function () {
    
  },
  /**
 * 生命周期函数--监听页面卸载
 */
  onUnload: function () {
    let that = this;
    clearInterval(that.data.inset);
    clearTimeout(that.data.timer);
  },
  /**
 * 页面上拉触底事件的处理函数
 */
  onReachBottom: function () {
    let that = this;
    pageNo++;
    likeList(that);

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let that=this;
    let gname=that.data.goods.goodsPinTuanVo.goodsName;
    let gimg=that.data.goods.bigImg;
    if(that.data.targetSharePath!='')
    {
      gimg=that.data.targetSharePath;
    }
    
    if(res.from === 'button'){
      if(res.target.dataset.type=='2'){//转发自己的拼团
        let fTit = '【仅剩' + res.target.dataset.num + '个】我' + res.target.dataset.price + '元拼了' + that.data.goods.goodsPinTuanVo.goodsName;
        return {  
          title: fTit, 
          path: '/pages/tuxedo/tuxedo?id=' + poodId + '&tuanid=' + res.target.dataset.id+ '&shareId=' + memberId, 
          imageUrl:gimg, 
          success: function (res) {}
        }
      }else{
          return {
            title: gname,
            path: '/pages/paired_detail/paired_detail?scene=' + poodId+ '&shareId=' + memberId,
            imageUrl:gimg,
            success: function (res) {},
          }
        }
      }
      return {
        title: gname,
        path: '/pages/paired_detail/paired_detail?scene=' + poodId+ '&shareId=' + memberId,
        imageUrl:gimg,
        success: function (res) {},
      }
    
  },
})